<?php

	/*
	*	example)
	*		$dbsess->create();
	*		$dbsess->sess_save(array("sex"=>"man","age"=>"20", "name"=>"이름"));
	*		$dbsess->sess_delete();
	*		$dbsess->sess_update(array("sex"=>"man","age"=>"20", "name"=>"성명"));
	*		$sess = $dbsess->sess_get('xmp');
	*		if($sess['has']){
	*			echo "signed";
	*		} else {
	*			echo "unsigned";
	*		}
	*		$dbsess->destroy();
	*		$dbsess->display();
	*/
	class DBSession {
		private $table_name = 'ggo_cfg_db_sessions';
		private $session_check = '';

		public function __construct($db){
			$this->db = $db;
			$this->set_session_check();
		}

		# 세션 체크 항목 설정
		public function set_session_check() {
			$this->session_check = $_SERVER['SERVER_NAME'];
		}

		# 세션 생성
		public function create() {
			$query = "
				CREATE TABLE IF NOT EXISTS `{$this->table_name}` (
					`session_key`		VARCHAR(64)					NOT NULL DEFAULT ''						COMMENT '키',
					`session_value`		TEXT						NOT NULL								COMMENT '값',
					`session_expiry`	INT(11)			UNSIGNED	NOT NULL DEFAULT '0'					COMMENT '만료기간',
					`session_check`		VARCHAR(250)				NOT NULL DEFAULT ''						COMMENT '세션체크',
					`ip`				VARCHAR(19)					NOT NULL DEFAULT ''						COMMENT '아이피',
					`ldate`				DATETIME					NOT NULL DEFAULT '0000-00-00 00:00:00'	COMMENT '인증시간',
					PRIMARY KEY (`session_key`),
					KEY `session_key` (`session_key`),
					KEY `ip` (`ip`),
					KEY `session_expiry` (`session_expiry`)
				) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
			$this->db->query($query);
		}

		# 세션 비움
		public function destroy() {
			$query = sprintf("TRUNCATE TABLE `%s`", $this->table_name);
			$this->db->query($query);
		}

		# 세션 정보 보기
		# 종속성 : TableTool
		public function display() {
			$tbltool = new TableTool();
			$article = $this->db->gets(sprintf("SELECT * FROM `%s`", $this->table_name));
			if($article['has']){
				echo "has session data";
				echo $tbltool->array_to_table($article['res']);
			} else {
				echo "has not session data";
			}
		}

		# 모든 세션 정보 리턴
		public function get_sessions_list($arg1, $arg2) {
			$article = $this->db->gets($q=sprintf("SELECT * FROM `%s` ORDER BY `session_expiry` DESC LIMIT %s, %s", $this->table_name, $arg1, $arg2));
			//Nlog::puts('$article', $article);
			if($article['has']){
				return $article;
			} else {
				return FALSE;
			}
		}

		# 세션 겟
		public function sess_get($data_print=''){
			$ret = $this->db->get(sprintf("SELECT * FROM `%s` WHERE `session_key` = '%s' AND `session_expiry` > '%s' ORDER BY `session_expiry` DESC LIMIT 1", $this->table_name, session_id(), time()));
			if($ret['has']){
				if($ret['res']['session_value'] != ''){
					$data = json_decode($ret['res']['session_value'], true);
					foreach($data as $key=>$val){
						//echo urldecode($val);
						$ret['res']['session_val'][$key] = urldecode($val);
					}
				}
			}
			if($data_print != ''){
				Nlog::xmp($ret);
			}
			return $ret;
		}

		# 세션 저장
		public function sess_save($data_array){
			#	array('decade' => 315576000, 'year' => 31557600, 'month' => 2629800, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'min' => 60, 'sec' => 1);
			$sess_life = get_cfg_var("session.gc_maxlifetime");
			$sess_life = $sess_life + 86400;
			$sess_life = time()+$sess_life;

			if(is_array($data_array)){
				foreach($data_array as $key=>$val){
					$data_arr[$key] = urlencode($val);
				}
				$json_data = json_encode($data_arr);
			} else {
				$json_data = NULL;
			}

			$data = array(
				"session_key"		=> session_id(),
				"session_value"		=> $json_data,
				"session_expiry"	=> $sess_life,
				"session_check"		=> $this->session_check,
				"ip"				=> $_SERVER['REMOTE_ADDR'],
				"ldate"				=> date('Y-m-d H:i:s')
			);
			//Nlog::xmp($data);

			foreach($data as $key => $val){
				$valstr[] = sprintf("`%s` = '%s'", $key, addslashes($val));
			}
			//Nlog::xmp($valstr);
			//Nlog::xmp(implode(', ', $valstr));
			$ret = $this->db->query(sprintf("REPLACE INTO `%s` SET %s", $this->table_name, implode(', ', $valstr)));
			//Nlog::xmp( sprintf("REPLACE INTO `%s` SET %s", $this->table_name, implode(', ', $valstr)) );
			$ret = $this->db->query(sprintf("DELETE FROM `%s` WHERE `session_expiry` < '%s'", $this->table_name, time()));

			return TRUE;
		}


		# 세션 삭제
		public function sess_delete(){
			$ret = $this->db->query(sprintf("DELETE FROM `%s` WHERE `session_key` = '%s'", $this->table_name, session_id()));
			if((int)$ret >= 1) return (int)$ret;
		}

		# 세션 업데이트
		public function sess_update($data_array){
			if(is_array($data_array)){
				foreach($data_array as $key=>$val){
					$data_arr[$key] = urlencode($val);
				}
				$json_data = json_encode($data_arr);
			} else {
				$json_data = NULL;
			}


			$sql = sprintf("UPDATE `%s` SET `session_value`='%s' WHERE `session_key`='%s'", $this->table_name, $json_data, session_id());
			$ret = $this->db->query($sql);
			//echo $ret;
			if((int)$ret >= 1) return (int)$ret;

		}

		public function __destruct(){
			//$this->db->close();
		}

	}